# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseBadRequest

from django.views.decorators.csrf import csrf_exempt
from wechat_sdk.basic import WechatBasic
from wechat_sdk.context.framework.django import DatabaseContextStore
from wechat_sdk.messages import (TextMessage, VoiceMessage, ImageMessage,
    VideoMessage, LinkMessage, LocationMessage, EventMessage
)

from xiaobai import settings
from wechat_sdk.messages import TextMessage
from wchat.models import KeyWord as KeyWordModel

from util import weather

token = settings.TOKEN
app_id = settings.APP_ID
app_sercet = settings.APP_SECRET

wChat = WechatBasic(token=token,appid=app_id,appsecret=app_sercet)

@csrf_exempt
def index(request):
    if request.method == 'GET':
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        echostr = request.GET.get('echostr', '')

        if not wChat.check_signature(signature, timestamp, nonce):
            return HttpResponseBadRequest('Verify Failed')
        return HttpResponse(echostr, content_type="text/plain")
        
    if request.method == 'POST':
        try:
            wChat.parse_data(data=request.body)
        except:
            return HttpResponseBadRequest('Invalid XML Data')
        
        #获取解析好的微信请求信息
        message = wChat.get_message()
        #利用本次请求中的用户openid来初始化上下文对话
        context = DatabaseContextStore(openid=message.source)

        response = None
        
        if isinstance(message, TextMessage):
            step = context.get('step', 1)
            #获取当前对话内容
            content = message.content.strip().encode('utf-8')

            if "天气" in content:
                reply_text = '请回复"tq+城市名"获取对应城市天气'
            elif 'tq' in content:
                reply_text = weather.city_weather(content)
            else:
                reply_text = '输入错误，请重新输入'
        elif isinstance(message, VoiceMessage):
            reply_text = '语音信息我听不懂/:P-(/:P-(/:P-('
        elif isinstance(message, ImageMessage):
            reply_text = '图片信息我也看不懂/:P-(/:P-(/:P-('
        elif isinstance(message, VideoMessage):
            reply_text = '视频我不会看/:P-('
        elif isinstance(message, LinkMessage):
            reply_text = '链接信息'
        elif isinstance(message, LocationMessage):
            reply_text = '地理位置信息'
        elif isinstance(message, EventMessage):  # 事件信息
            if message.type == 'subscribe':  # 关注事件(包括普通关注事件和扫描二维码造成的关注事件)
                follow_event = KeyWordModel.objects.get(keyword='关注事件')
                reply_text = follow_event.content
                
                # 如果 key 和 ticket 均不为空，则是扫描二维码造成的关注事件
#                 if message.key and message.ticket:
#                     reply_text += '\n来源：扫描二维码关注'
#                 else:
#                     reply_text += '\n来源：搜索名称关注'
                    
            elif message.type == 'unsubscribe':
                reply_text = '取消关注事件'
            elif message.type == 'scan':
                reply_text = '已关注用户扫描二维码！'
            elif message.type == 'location':
                reply_text = '上报地理位置'
            elif message.type == 'click':
                reply_text = '自定义菜单点击'
            elif message.type == 'view':
                reply_text = '自定义菜单跳转链接'
            elif message.type == 'templatesendjobfinish':
                reply_text = '模板消息'

        response = wChat.response_text(content=reply_text)
        return HttpResponse(response, content_type="application/xml")